package com.yl.paymanagement.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.Goods;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.yl.paymanagement.config.PayConfig;
import com.yl.paymanagement.dao.RechargeDao;
import com.yl.paymanagement.dao.YlFrontAccountDao;
import com.yl.paymanagement.pojo.RechargeRecoding;
import com.yl.paymanagement.pojo.YlFrontAccount;
import com.yl.paymanagement.pojo.YlPayModel;
import com.yl.paymanagement.service.AlipayService;
import com.yl.paymanagement.service.RechargeRecodingService;
import com.yl.paymanagement.utils.GenerateNum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;


@Service
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    PayConfig payConfig;

    @Autowired
    RechargeDao rechargeDao;

    @Autowired
    YlFrontAccountDao ylFrontAccountDao;

    /*@Autowired
    YlSystemFeign ylSystemFeign;*/

    RedisTemplate<String,YlPayModel> redisTemplate;
    public  AlipayClient getAlipayClient(){
        AlipayClient alipayClient = new DefaultAlipayClient(payConfig.URL,payConfig.APPID,
                payConfig.RSA_PRIVATE_KEY, "json", payConfig.CHARSET,
                payConfig.ALIPAY_PUBLIC_KEY, payConfig.SIGNTYPE);
        return alipayClient;
    }
    @Override
    public String alipayRecharge(YlPayModel ylPayModel) throws AlipayApiException {

        AlipayClient alipayClient = getAlipayClient();

        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();

        JSONObject bizContent = new JSONObject();

        String tradeNo = GenerateNum.generateOrder()+"";

        //设置订单号
        bizContent.put("out_trade_no", ""+tradeNo);

        //设置总金额
        bizContent.put("total_amount", ylPayModel.getTotal_amount());
        alipayTradePagePayRequest.setNotifyUrl(payConfig.notify_url);
        alipayTradePagePayRequest.setReturnUrl(payConfig.return_url);

        //设置对付款的订单标题
        bizContent.put("subject", ylPayModel.getSubject());

        //订单相对超时时间
        bizContent.put("timeout_express", "10m");

        //商家和支付宝签约的产品码
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        alipayTradePagePayRequest.setBizContent(bizContent.toString());

        AlipayTradePagePayResponse alipayTradePagePayResponse = alipayClient.pageExecute(alipayTradePagePayRequest);

        if (!alipayTradePagePayResponse.isSuccess()){
            throw new RuntimeException("阿里支付调用失败");
        }

        Date date = new Date();
        RechargeRecoding rechargeRecoding = new RechargeRecoding();
        rechargeRecoding.setPeopleId(ylPayModel.getYlFrontAccount().getAccountId());
        rechargeRecoding.setPayMethod(ylPayModel.getPayType());
        rechargeRecoding.setRechargeMoney(ylPayModel.getTotal_amount());
        rechargeRecoding.setRechargeNum(tradeNo);
        rechargeRecoding.setCardNum(ylPayModel.getYlFrontAccount().getAccountCardNumber());
        rechargeRecoding.setRechargeType(ylPayModel.getSubject());
        rechargeRecoding.setRechargeTime(date);
        rechargeDao.addByRechargeRecoding(rechargeRecoding);
        return alipayTradePagePayResponse.getBody();
    }

    @Override
    public String aliPayOther(YlPayModel ylPayModel) {
        AlipayClient alipayClient = getAlipayClient();

        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();

        JSONObject bizContent = new JSONObject();

        //设置订单号
        bizContent.put("out_trade_no", ""+GenerateNum.generateOrder());

        //设置总金额
        bizContent.put("total_amount", ylPayModel.getTotal_amount());

        //设置对付款的订单标题
        bizContent.put("subject", ylPayModel.getSubject());
        if (!(ylPayModel.getGoodsList()==null)){
            //设置商品的详细信息
            JSONArray goodsDetail = new JSONArray();
            for (Goods goods : ylPayModel.getGoodsList()) {
                JSONObject jsonObject = new JSONObject();

                //商品Id
                jsonObject.put("goods_id", goods.getGoodsId());

                //商品名称
                jsonObject.put("goods_name", goods.getGoodsName());

                //商品数量
                jsonObject.put("quantity", goods.getGoodsNum());

                //商品单价
                jsonObject.put("price", goods.getGoodsPrice());

                goodsDetail.add(jsonObject);
            }

            bizContent.put("goods_detail", goodsDetail);
        }


        //订单相对超时时间
        bizContent.put("timeout_express", "10m");

        //商家和支付宝签约的产品码
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        alipayTradePagePayRequest.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse alipayTradePagePayResponse=null;
        try {
            alipayTradePagePayResponse = alipayClient.pageExecute(alipayTradePagePayRequest);

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return alipayTradePagePayResponse.getBody();
    }

    @Override
    @Transactional
    public String cardPay(YlPayModel ylPayModel) {
        YlFrontAccount yl = ylFrontAccountDao.findById(ylPayModel.getYlFrontAccount().getAccountId());

        if (yl.getCardBalance().compareTo(ylPayModel.getTotal_amount())==-1){
            throw new RuntimeException("余额不足");
        }else {
            BigDecimal subtract = yl.getCardBalance().subtract(ylPayModel.getTotal_amount());
            yl.setCardBalance(subtract);
            ylFrontAccountDao.editBMoney(yl);
        }

        return null;
    }
}
